package com.fansl.koala.quickdev.common.bean;

import com.fansl.koala.quickdev.common.enums.ResultEnum;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * @author fansl
 * @Description: 响应信息主体
 * @date 2020/3/12 12:07
 */
@AllArgsConstructor
@Accessors(chain = true)
@Builder
public class R<T> implements Serializable {
    @Getter
    @Setter
    private int code = ResultEnum.SUCCESS.getCode();
    @Getter
    @Setter
    private String message = ResultEnum.SUCCESS.getMessage();
    @Getter
    @Setter
    private T data;

    public R (){
        super();
    }

    public R(T data){
        super();
        this.data = data;
    }

    public R(T data, String message) {
        super();
        this.data = data;
        this.message = message;
    }

    public R(Throwable e) {
        super();
        this.message = e.getMessage();
        this.code = ResultEnum.FAILED.getCode();
    }

    public R(ResultEnum resultEnum, T data) {
        super();
        this.message = resultEnum.getMessage();
        this.code = resultEnum.getCode();
        this.data = data;
    }

    public static <T> R<T> ok(T data){
        R<T> result = new R();
        result.setData(data)
                .setCode(ResultEnum.SUCCESS.getCode())
                .setMessage(ResultEnum.SUCCESS.getMessage());
        return result;
    }

    public static <T> R<T> failed(String message){
        R<T> result = new R();
        result.setCode(ResultEnum.FAILED.getCode())
                .setMessage(message);
        return result;
    }

    public static <T> R<T> failed(ResultEnum resultEnum){
        R<T> result = new R();
        result.setCode(resultEnum.getCode())
                .setMessage(resultEnum.getMessage());
        return result;
    }
}
